package com.tbycoder.tby.utils;


import com.tbycoder.tby.entity.Vo.FileVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 *
 * @author zuozhiwei
 *
 * 在调用以下接口时候都需要在类中声明如下两条语句
 * @javax.annotation.Resource
 * FileUtil fileUtil;
 */
@Component
public class FileUtil {

    Logger logger = LoggerFactory.getLogger(FileUtil.class);

    @Value("${file.uploadPath}")
    String uploadPath;

    @Value("${file.domain}")
    String domain;



    /**
     * 文件在本地存储的地址
     */
    private Path fileStorageLocation = null;


    /**
     * 存储文件到系统
     * @param file 文件
     * @param folder 文件夹 默认不传，可以传null
     * @return 文件id
     */
    public FileVo storeFileInDatabase(MultipartFile file, String folder) {

        this.getLocation();
        // 完整文件名
        String originName = StringUtils.cleanPath(file.getOriginalFilename());
        // 文件名后缀，最后一个.后面的
        String ext = originName.substring(originName.lastIndexOf("."));
        //通过文件名来获取作业名
        String homeworkName = originName.substring(0,originName.lastIndexOf("."));
        // 文件名拼接
        String fileName = originName.substring(0,originName.lastIndexOf(".")) + "-" + System.currentTimeMillis() + ext;
        if (folder != null && !"".equals(folder)) {
            folder = clearFilePath(folder);
            fileName = folder + "/" + fileName;
        }
        try {
            // Check if the file's name contains invalid characters
            if(fileName.contains("..")) {
                throw new Exception("Sorry! Filename contains invalid path sequence " + fileName);
            }
            // Copy file to the target location (Replacing existing file with the same name)
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            System.out.println("文件地址为："+targetLocation.toString());
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            String fileId = "sf-"+ UUID.randomUUID();
            return FileVo.builder()
                    .fileId(fileId)
                    .fileName(fileName)
                    .originName(originName)
                    .build();
        } catch (Exception ex) {
            logger.error("上传文件到数据库中发生异常",ex);
        }
        return null;
    }




    /**
     * 清理路径中间的多余的/
     * @param source
     * @return
     */
    public String clearFilePath(String source) {
        String element = File.separator;
        source = StringUtil.trim(source,element);
        while (source.contains(element+element)) {
            source = source.replace(element+element,element);
        }
        return source;
    }

    /**
     * 创建对象
     */
    private void getLocation(){
        System.out.println(uploadPath);
        this.fileStorageLocation = Paths.get(uploadPath).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ignored) {

        }
    }
}
